﻿var map;
var circles = [];

$(function () {
    map = L.map("map").setView([30.9578, 121.3033], 14);
	var mapTiles = L.layerGroup([
		L.tileLayer(
			"http://{s}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}", 
			{ 
				attribution: "&copy; <a href='http://www.tianditu.com/map/index.html'>天地图</a>", 
				subdomains: ["t2", "t3", "t4", "t5", "t6"], 
				detectRetina: true, 
				reuseTiles: true,
				zIndex: 0
			}
		), 
		L.tileLayer(
			"http://{s}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}", 
			{ 
				attribution: "&copy; <a href='http://www.tianditu.com/map/index.html'>天地图</a>", 
				subdomains: ["t2", "t3", "t4", "t5", "t6"], 
				detectRetina: true, 
				reuseTiles: true,
				zIndex: 0
			}
		)
	]).addTo(map);
	$.ajax("api/Images").done(function (images) {
	    for (var i = 0; i < images.length; i++) {
	        var circle = L.circle([images[i].latitude, images[i].longitude], 2);
	        circle.on("click", circleClickHandler(i, images[i]));
	        circle.addTo(map);
	        circles.push(circle);
	    }
	    circles[25].fireEvent("click");
	});
});

var loadPano = function (url) {
    var div = $("#pano")[0];
    var PSV = new PhotoSphereViewer({
        panorama: url,
        container: div,
        time_anim: false,
        navbar: true,
        tilt_up_max: 40,
        size: {
            width: "100%",
            height: $("#pano").height() + "px"
        },
        long_offset: Math.PI / 1080,
        lat_offset: Math.PI / 1080,
        usexmpdata: false,
        cropped_height_coef: 0.7,
        start_theta: 5
    });
};

var circleClickHandler = function (index, image) {
    return function (e) {
        for (var i = 0; i < circles.length; i++)
            if (i !== index)
                circles[i].setStyle({ color: "#03f", className: "" }).setRadius(2);
        circles[index].setStyle({ color: "#F44336", className: "selected" }).setRadius(4);
        $("#lng").text(new Angle(image.longitude).toString(2));
        $("#lat").text(new Angle(image.latitude).toString(2));
        $("#date").text(image.dateTime || "无");
        loadPano("api/Image/" + image.name);
    };
};

var Angle = function (value) {
    if (typeof value !== "number")
        throw new TypeError();
    var obj = {};
    obj.degree = Math.floor(value);
    obj.minute = Math.floor((value - obj.degree) * 60);
    obj.second = ((value - obj.degree) * 60 - obj.minute) * 60;
    obj.toString = function (fractionDigits) {
        return obj.degree + "d" + ("00" + obj.minute).slice(-2) + "'" + ("00" + obj.second.toFixed(fractionDigits)).slice(-fractionDigits - 3) + '"';
    };
    return obj;
};